<template>
	<el-form size="medium" ref="tableForm" :model="tableForm" class="custom_select_wrapper">
		<el-table :data="tableForm.lists" size="medium" border>
			<el-table-column label="追责时间" min-width="180">
				<template slot-scope="{ row, $index }">
					<el-form-item :prop="`lists.${$index}.accountabilityTime`" :rules="tableRules.accountabilityTime">
						<el-date-picker v-model="row.accountabilityTime" type="date" placeholder="选择追责时间"></el-date-picker>
					</el-form-item>
				</template>
			</el-table-column>
			<el-table-column label="追责原因" min-width="700">
				<template slot-scope="{ row, $index }">
					<el-form-item :prop="`lists.${$index}.accountabilityCause`" :rules="tableRules.accountabilityCause">
						<el-input v-model="row.accountabilityCause" placeholder="输入追责原因"></el-input>
					</el-form-item>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="54" align="center">
				<template slot-scope="{ row, $index }">
					<el-button class="del" type="text" size="small" icon="el-icon-delete" @click="handleDeleteUser($index)"></el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-button type="primary" size="small" class="add" @click="handleAddedUser()">新增一位</el-button>
	</el-form>
</template>

<script>
import emitter from 'element-ui/src/mixins/emitter';
export default {
	mixins: [emitter],
	props: {
		value: { type: Array, default: () => [] },
		list: { type: Array, default: () => [] }
	},
	data() {
		return {
			tableForm: {
				lists: this.value
			},
			tableRules: {
				accountabilityTime: [{ required: true, message: '请选择追责时间', trigger: 'change' }],
				accountabilityCause: [{ required: true, message: '请输入追责原因', trigger: 'blur' }]
			}
		};
	},
	watch: {
		value(arr) {
			this.$set(this.tableForm, 'lists', arr);
		},
		'tableForm.lists'(arr) {
			this.$emit('input', arr);
			this.dispatch('ElFormItem', 'el.form.change', [arr]);
		}
	},
	methods: {
		async handleAddedUser() {
			if (!(await this.validChildForm())) return false;
			this.tableForm.lists.push({ accountabilityTime: '', accountabilityCause: '' });
		},

		handleDeleteUser(index) {
			this.tableForm.lists.splice(index, 1);
		},

		validChildForm() {
			return new Promise((resolve) => {
				this.$refs['tableForm'].validate((valid) => {
					resolve(valid);
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.custom_select_wrapper::v-deep {
	width: 100%;
	.el-button.del {
		font-size: 16px;
	}
	.el-button.add {
		margin-top: 10px;
	}
}
</style>
